package com.xinke.query.common.exception.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.xinke.query.common.exception.GaoSuQueryException;
import com.xinke.query.common.result.Result;
import com.xinke.query.common.result.ResultCodeEnum;
import com.xinke.query.common.utils.GaoSuInfoUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(GaoSuQueryException.class)
    public Result handlerGaoSuQueryException(GaoSuQueryException e, HttpServletRequest request) {
        //记录异常日志
        log.error("异常: code:{},message:{}", e.getCode(), e.getMessage());
        Result<Object> result = Result.build(null, e.getCode(), e.getMessage());
        return result;
    }

    /**
     * controller参数校验异常处理器 基于@Validated 如@Min(1)
     * 数据校验失败的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handlerConstrainViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder errorMsg = new StringBuilder();
        for (ConstraintViolation<?> violation : violations) {
            errorMsg.append(violation.getMessage()).append(";");
        }
        log.error("异常: code:{},message:{}:{}", ResultCodeEnum.PARAM_VALIDATION_FAILED.getCode(), ResultCodeEnum.PARAM_VALIDATION_FAILED.getMessage(), errorMsg.toString());
        return Result.fail(ResultCodeEnum.PARAM_VALIDATION_FAILED, errorMsg.toString());
    }

    /**
     * controller参数校验异常处理器 基于@Validated 如@Validated
     * 方法参数检验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result HandlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errors = new HashMap<>();
        //后去参数检验失败的map关系
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        String errorMsg = GaoSuInfoUtils.mapToString(errors);
        log.error("异常: code:{},message:{}:{}", ResultCodeEnum.PARAM_VALIDATION_FAILED.getCode(), ResultCodeEnum.PARAM_VALIDATION_FAILED.getMessage(), errorMsg);
        return Result.fail(ResultCodeEnum.PARAM_VALIDATION_FAILED, errorMsg);
    }

    /**
     * json参数异常捕获类: mysql->java错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(InvalidFormatException.class)
    public Result HandlerExceptionHandler(ExceptionHandler e) {
        log.error("异常: code:{},message:{}:{}", ResultCodeEnum.PARAM_VALIDATION_FAILED.getCode(), ResultCodeEnum.PARAM_VALIDATION_FAILED.getMessage(), "json参数解析失败");
        return Result.fail(ResultCodeEnum.PARAM_VALIDATION_FAILED, "json参数解析失败");
    }

    /**
     * json参数异常捕获类: json->java错误
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        log.error("异常: code:{},message:{}:{}", ResultCodeEnum.PARAM_VALIDATION_FAILED.getCode(), ResultCodeEnum.PARAM_VALIDATION_FAILED.getMessage(), "json参数解析失败");
        return Result.fail(ResultCodeEnum.PARAM_VALIDATION_FAILED, "json参数解析失败");
    }

    /**
     * Enum解析失败；没有对应的QueryType
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(JsonProcessingException.class)
    public Result handleJsonProcessingException(JsonProcessingException ex) {
        log.error("异常: code:{},message:{}:{}", ResultCodeEnum.QUERY_TYPE_NOT_EXIST.getCode(), ResultCodeEnum.QUERY_TYPE_NOT_EXIST.getMessage(), "json参数解析失败");
        return Result.fail(ResultCodeEnum.QUERY_TYPE_NOT_EXIST);
    }

    /**
     * 处理所有未被捕获的异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result error(Exception e, HttpServletRequest request) {
        //记录异常日志
        Result<Object> result = Result.build(null, 500, "服务器内部错误，请联系管理员！");
        return result;
    }


}
